<template>
  <div style="width: 55%; margin: 0 auto; margin-top: 5%">
    <el-card class="box-card1">
      <div slot="header" class="clearfix">
        <span>个人信息</span>
      </div>
      <el-descriptions class="margin-top" title="" :column="1" :model="User">
        <template slot="extra">
          <div class="demo-basic--circle">
            <div class="block">
              <el-avatar :size="100" :src="User.user_photo"></el-avatar>
            </div>
          </div>
        </template>
        <el-descriptions-item label="用户名">{{
          User.user_name
        }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{
          User.user_telephone
        }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{
          User.user_sex
        }}</el-descriptions-item>
        <el-descriptions-item label="账户余额">{{
          User.member.balance
        }}</el-descriptions-item>
        <el-descriptions-item label="信息修改">
          <el-button
            style="padding: 3px 0"
            type="text"
            @click="dialogFormVisible = true"
            >修改个人信息</el-button
          >
          <el-button style="padding: 3px 0"
            type="text" @click="updPhotoVisible=true">修改头像</el-button>
        </el-descriptions-item>
        <el-descriptions-item label="余额操作">
          <el-button
            size="small"
            type="primary"
            plain
            @click="addVisible = true"
            >充值</el-button
          >
          <el-button
            size="small"
            type="primary"
            plain
            @click="subtractVisible = true"
            >提现</el-button
          >
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <!-- 修改个人信息 -->
    <el-dialog
      title="修改个人信息"
      :visible.sync="dialogFormVisible"
      width="30%"
    >
      <el-form :model="User" :rules="rules1" ref="User">
        <el-form-item label="用户名" prop="user_name" :label-width="formLabelWidth">
          <el-input v-model="User.user_name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="user_telephone" :label-width="formLabelWidth">
          <el-input v-model="User.user_telephone"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-radio-group v-model="User.user_sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="updUser('User')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 增加余额 -->
    <el-dialog title="余额充值" :visible.sync="addVisible" width="30%">
      <el-form :model="addBalance" :rules="rules2"  ref="addBalance">
        <el-form-item label="充值金额" prop="balance1" :label-width="formLabelWidth">
          <el-input v-model.number="addBalance.balance1"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm1('addBalance')">取 消</el-button>
        <el-button type="primary" @click="recharge('addBalance')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 余额提现 -->
    <el-dialog title="余额提现" :visible.sync="subtractVisible" width="30%">
      <el-form :model="updBalance" :rules="rules3" ref="updBalance">
        <el-form-item label="提现金额" prop="balance2" :label-width="formLabelWidth">
          <el-input v-model.number="updBalance.balance2"></el-input>
        </el-form-item>
        <div style="color: #c0c4cc">
          最高提现金额：{{ User.member.balance }}元
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm2('updBalance')">取 消</el-button>
        <el-button type="primary" @click="withdraw('updBalance')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 头像修改 -->
    <el-dialog title="修改头像" :visible.sync="updPhotoVisible" width="30%">
      <el-form>
        <el-form-item label="">
          <el-upload
            ref="upload"
            :action="reqUrl"
            list-type="picture-card"
            :http-request="uploadSectionFile"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updUserPhoto()">上 传</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  inject:['reload'],
  data() {
    return {
      imageUrl: "",
      reqUrl:"",
      User: {
        user_id: "",
        user_name: "",
        user_telephone: "",
        user_sex: "",
        user_photo: "",
        member: {
          id: "",
          balance: "",
        },
      },
      dialogFormVisible: false,
      formLabelWidth: "80px",
      addVisible: false,
      addBalance: {
        balance1: ''
      },
      subtractVisible: false,
      updBalance: {
        balance2: ''
      },
      updPhotoVisible: false,
      rules1:{
        user_name:[
            { required: true, message: "请输入用户名", trigger: "blur" },
            { min: 2, max: 7, message: "长度在3到10个字符", tregger: "blur" },
            {pattern: /^[\u4E00-\u9FA5]+$/, message: '用户名只能为中文'}
          ],
        user_telephone:[
            { required: true, message: "请输入电话号码", trigger: "blur" },
            { min: 11, max: 11, message: "请输入11位手机号码", tregger: "blur" },
            { 
              pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
              message: '请输入正确的手机号码'
            }
          ],
        },
      rules2:{
        balance1:[
            { required: true, message: '充值金额不能为空'},
            { type: 'number', message: '金额必须为数字值'}
        ],
      },
      rules3:{
        balance2:[
            { required: true, message: '提现金额不能为空'},
            { type: 'number', message: '金额必须为数字值'}
        ],
      }
    };
  },
  methods: {
    getOneUser() {
      var id = sessionStorage.getItem("userId");
      this.$axios
        .get("/userinfo/" + id)
        .then((res) => {
          this.User = res.data.data;
        })
        .catch((error) => {
          alert(res.data.messages);
        });
    },
    updUser(User) {
      this.$refs[User].validate((valid) => {
        if (valid) {
          this.saveUser();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    cancel(){
      this.dialogFormVisible = false;
      this.getOneUser();
    },
    recharge(addBalance) {
      this.$refs[addBalance].validate((valid) => {
        if (valid) {
          var Balance = Number(this.User.member.balance) + Number(this.addBalance.balance1);
          this.$axios.put("/member", {
            user_id: this.User.user_id,
            balance: Balance,
          })
          .then((res) => {
            alert("充值成功");
            this.addVisible = false;
            this.getOneUser();
          })
          .catch((error) => {
            alert(res.data.messages);
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    withdraw(updBalance) {
      this.$refs[updBalance].validate((valid) => {
        if (valid) {
          if (Number(this.updBalance.balance2) > Number(this.User.member.balance)) {
            alert("余额不足，无法提现");
          } else {
            var Balance = Number(this.User.member.balance) - Number(this.updBalance.balance2);
            this.$axios.put("/member", {
                user_id: this.User.user_id,
                balance: Balance,
            })
            .then((res) => {
              alert("提现成功");
              this.subtractVisible = false;
              this.getOneUser();
            })
            .catch((error) => {
              alert(res.data.messages);
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    saveUser(){
      this.$axios.put("/userinfo/", this.User)
      .then((res) => {
        alert(res.data.messages);
        this.dialogFormVisible = false;
        this.getOneUser();
      })
      .catch((error) => {
        alert(res.data.messages);
      });
    },
    updUserPhoto(){
      let formData = new FormData();
      formData.append("user_id", this.User.user_id);
      //将文件封装到formData类型的对象中，名称为headimg1
      //headimg1是一个自定义名称，需要和服务器端接收文件的参数名称吻合
      formData.append("headimg1", this.User.user_photo);
      if (this.User.user_photo == "error" || this.User.user_photo == ""){
        alert("请上传小于2M的JPG格式的头像");
      }
      else{
        let config = {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        };
        this.$axios.post("/userinfo/photo", formData, config)
        .then((res) => {
          alert(res.data.messages);
          this.updPhotoVisible = false;
          this.$refs.upload.clearFiles();
          this.getOneUser();
          this.reload();
        })
        .catch((error) => {
          alert(res.data.messages);
        });
      }
    },
    resetForm1(addBalance) {
      this.$refs[addBalance].resetFields();
      this.addVisible = false;
    },
    resetForm2(updBalance) {
      this.$refs[updBalance].resetFields();
      this.subtractVisible = false;
    },
    uploadSectionFile(params){
      this.User.user_photo =params.file;
    },
    getFile(e) {
      this.User.user_photo = e.target.files[0];
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  },
  mounted() {
    this.getOneUser();
  },
};
</script>

<style>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card1 {
  width: 600px;
}
</style>